package cumeo89.chii.client.ui;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class AutoResizeTextBox extends TextBox {

	private static Label measurer;

	static {
		measurer = new Label();
		measurer.setStyleName("measurer");
		RootPanel.get().add(measurer, -1000, -1000);
	}

	private int minWidth = 0;
	private int maxWidth = Integer.MAX_VALUE;
	private boolean resizeSupressed = false;

	public AutoResizeTextBox() {
		sinkEvents(Event.ONKEYDOWN);
	}

	@Override
	public void onBrowserEvent(Event event) {
		super.onBrowserEvent(event);
		if (DOM.eventGetType(event) == Event.ONKEYDOWN) {
			resize();
		}
	}

	@Override
	public void setText(String text) {
		super.setText(text);
		resize();
	}

	private void resize() {
		if (resizeSupressed) {
			return;
		}
		resizeSupressed = true;
		measurer.setText(this.getText());
		int width = measurer.getOffsetWidth() + 30;
		if (width < minWidth) {
			width = minWidth;
		}
		if (width > maxWidth) {
			width = maxWidth;
		}
		if (width != getOffsetWidth()) {
			setWidth(width + "px");
		}
		resizeSupressed = false;
	}

	public int getMinWidth() {
		return minWidth;
	}

	public void setMinWidth(int minWidth) {
		this.minWidth = minWidth;
		resize();
	}

	public int getMaxWidth() {
		return maxWidth;
	}

	public void setMaxWidth(int maxWidth) {
		this.maxWidth = maxWidth;
		resize();
	}

	public boolean isResizeSupressed() {
		return resizeSupressed;
	}

	public void setResizeSupressed(boolean resizeSupressed) {
		this.resizeSupressed = resizeSupressed;
		if (!resizeSupressed) {
			resize();
		}
	}

}
